package cn.sciento.transfer.app.service.impl;

import cn.sciento.core.base.BaseConstants;
import cn.sciento.transfer.api.controller.v1.EventSendController;
import cn.sciento.transfer.app.service.EventErrorService;
import cn.sciento.transfer.app.service.EventSendArchService;
import cn.sciento.transfer.app.service.MessageSendService;
import cn.sciento.transfer.domain.entity.EventError;
import cn.sciento.transfer.domain.entity.EventSend;
import cn.sciento.transfer.domain.repository.EventSendRepository;
import cn.sciento.transfer.infra.rocketmq.service.MqProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MessageSendServiceImpl implements MessageSendService {
  @Autowired
  private EventSendRepository eventSendRepository;
  
  @Autowired
  private EventSendArchService eventSendArchService;
  
  @Autowired
  private EventErrorService eventErrorService;
  
  @Autowired
  private MqProducerService mqProducerService;
  
  private static final Logger logger = LoggerFactory.getLogger(EventSendController.class);
  
  @Async("stong-transfer-executor")
  public void addMsgToMQ(EventSend eventSend) {
    eventSend.setProcessStatus("R");
    int sendOk = this.mqProducerService.sendMsg(eventSend.getMessages());
    if (sendOk == BaseConstants.Flag.YES) {
      eventSend.setProcessStatus("S");
      this.eventSendArchService.insertEventSendArch(eventSend);
    } else {
      eventSend.setProcessStatus("E");
      EventError eventError = EventError.getInstance(eventSend, "SEND", "send msg error,please check config");
      try {
        this.eventErrorService.insertEventSendError(eventError);
        eventSend.setProcessStatus("ER");
      } catch (Exception e2) {
        eventSend.setProcessStatus("ERE");
      } 
      this.eventSendRepository.updateOptional(eventSend, "processStatus");
    } 
  }
}
